package lovo.practice_7_14.dao.impl;

import lovo.practice_7_14.dao.BaseDAO;
import lovo.practice_7_14.dao.UserDAO;
import lovo.practice_7_14.pojo.UserDO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAOImpl extends BaseDAO implements UserDAO {
    @Override
    public UserDO getByUsernameAndPwd(String username, String pwd) {
        this.getConnection();
        statement = null;
        rs = null;
        UserDO userDO = null;
        String sql = "select  * from t_atm where a_account =? and a_password =? ";
        try {
            statement = con.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, pwd);
            rs = statement.executeQuery();
            if (rs.next()) {
                userDO = new UserDO();
                userDO.setAccount(rs.getString("a_account"));
                userDO.setPwd(rs.getString("a_password"));
                userDO.setBalance(rs.getDouble("a_balance"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close(con, statement, rs);
        }
        return userDO;
    }

    @Override
    public void update(UserDO userDO) {
        // 1. 创建连接
        this.getConnection();
//        PreparedStatement statement = null;
        try {
            // 2. 获取执行SQL语句对象
            String sql = "update t_atm set a_account=?,a_password=?,a_balance=? where a_account =?";

            statement = con.prepareStatement(sql);
            statement.setString(1, userDO.getAccount());
            statement.setString(2, userDO.getPwd());
            statement.setDouble(3, userDO.getBalance());
            statement.setString(4, userDO.getAccount());
            int row = statement.executeUpdate();
            System.out.println(row);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 4. 关闭连接
            close(con, statement);
        }
    }

}
